package com.autotest.nore.controller;

import com.autotest.nore.common.exception.TokenEmptyException;
import com.autotest.nore.common.utils.PageUtils;
import com.autotest.nore.common.utils.Pager;
import com.autotest.nore.domain.Operation;
import com.autotest.nore.dto.OperationDTO;
import com.autotest.nore.dto.OperationGroupDTO;
import com.autotest.nore.request.QueryRequest;
import com.autotest.nore.service.OperationService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.List;


@RestController
@RequestMapping("/autotest/operation")
public class OperationController {

    @Autowired
    private OperationService operationService;

    @PostMapping("/save")
    public void saveOperation(@RequestBody Operation operation, HttpServletRequest request) {
        HttpSession session = request.getSession(false); // 获取会话，如果不存在则返回null
        if (session == null || session.getAttribute("userName") == null) {
            throw new TokenEmptyException("用户未登录，请重新登录");
        }
        String userName = session.getAttribute("userName").toString();
        operation.setUpdateUser(userName);
        operationService.saveOperation(operation);
    }

    @PostMapping("/delete")
    public void deleteOperation(@RequestBody Operation operation) {
        operationService.deleteOperation(operation.getId(), operation.getUiType());
    }

    @GetMapping("/detail/{uiType}/{operationId}")
    public Operation getOperationDetail(@PathVariable String uiType, @PathVariable String operationId) {
        return operationService.getOperationDetail(operationId, uiType);
    }

    @GetMapping("/group/{uiType}/list/{projectId}")
    public List<OperationGroupDTO> getGroupOperationList(@PathVariable String uiType,@RequestParam String system, @PathVariable String projectId) {
        return operationService.getGroupOperationList(uiType, system, projectId);
    }

    @PostMapping("/list/{goPage}/{pageSize}")
    public Pager<List<OperationDTO>> getOperationList(@PathVariable int goPage, @PathVariable int pageSize,
                                                    @RequestBody QueryRequest request) {
        Page<Object> page = PageHelper.startPage(goPage, pageSize, true);
        return PageUtils.setPageInfo(page, operationService.getOperationList(request));
    }
}
